from html.parser import HTMLParser
import sys
import re
import pokeparser
import iteminfo

class item(HTMLParser):
	def __init__(self):
		super().__init__()
		self.in_h2 = self.in_h3 = self.in_table = self.in_td = self.in_jname = self.in_ename = self.in_des = False
		self.bag = self.type = self.url = self.cname = self.jname = self.ename = self.des = ''
		self.rows = 0
		self.parser = pokeparser.pokeparser()
		self.text = self.parser.gettext(self.parser.item())
		self.f = open('text/item.txt', 'a+', encoding='utf-8')
		self.u = open('url/itemurl.txt', 'a+', encoding='utf-8')
		with open('text/item.txt', encoding='utf-8') as f:
			self.startcount = len(f.readlines())
		self.count = 0
	def handle_starttag(self, tag, attrs):
		attrs = dict(attrs)
		iid = attrs.get('id','')
		title = attrs.get('title','')
		rows = attrs.get('rowspan','')
		if tag == 'h2':
			self.bag = self.type = ''
			self.in_h2 = True
		elif tag == 'h3':
			self.in_h3 = True
		# 获得背包属性：
		elif tag == 'span' and self.in_h2:
			self.bag = iid
			self.in_h2 = False
		elif tag == 'tbody':
			self.in_table = True
		elif tag == 'td':
			self.in_td = True
			# 一条描述占用多行：
			if self.in_des and rows != '':
				self.rows = int(rows)
		# 获得道具中文名：
		m = re.search('(.+?)（道具）',title)
		if m and self.in_td:
			self.cname = m.group(1)
			# 获得地址：
			self.url = self.parser.combine(attrs.get('href',''))
	def handle_data(self, data):
		data = str(data).strip('\n')
		# 获得道具属性：
		if self.in_h3 and data != '':
			self.type = data
			self.in_h3 = False
		elif self.in_td and self.cname != '' and data != '':
			# 获得道具日文名：
			if self.jname == '' and (self.cname == data or re.search(data+'（(.+?)）', self.cname)):
				self.in_jname = True
			elif self.in_jname:
				self.jname = data
				self.in_jname = False
				self.in_ename = True
			# 获得道具英文名：
			elif self.in_ename:
				self.ename = data
				self.in_ename = False
				if self.rows == 0:
					self.in_des = True
				# 道具共用同一条描述：
				elif self.rows > 0:
					self.rows = self.rows - 1
					self.in_des = False
					self.finish()
			# 获得道具描述：
			elif self.in_des:
				self.des = data
				self.in_des = False
				self.finish()

	def finish(self):
		self.count += 1
		if self.count > self.startcount:
			p = iteminfo.iteminfo(self.cname,self.url)
			p.feed(p.text)
			p.close()
			temp = sys.stdout
			sys.stdout = self.f
			item = [self.cname,self.jname,self.ename,self.des,self.bag,self.type,p.info,p.fling,p.effect]
			print(item)
			self.f.flush()
			sys.stdout = self.u
			print(self.url)
			self.u.flush()
			sys.stdout = temp
			print(item)
		self.url = self.cname = self.jname = self.ename = ''
	
	def handle_endtag(self, tag):
		if tag == 'h2':
			self.in_h2 = False
		elif tag == 'h3':
			self.in_h3 = False
		elif tag == 'tbody':
			self.in_table = False
		elif tag == 'td':
			self.in_td = False

def writetext():
	i = item()
	i.feed(i.text)
	i.close()

if __name__ == "__main__":
	writetext()